const icon = `<svg data-name="Layer 1" id="Layer_1" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs><style>.cls-1{fill:#ba63c6;}</style></defs><title/><path class="cls-1" d="M31.79,28.11l-7-14a2,2,0,0,0-3.58,0L18,20.56,15.3,18.73A17.13,17.13,0,0,0,19.91,9H22a2,2,0,0,0,0-4H14V3a2,2,0,0,0-4,0V5H2A2,2,0,0,0,2,9H15.86a13.09,13.09,0,0,1-3.79,7.28,13.09,13.09,0,0,1-3.19-4.95,2,2,0,1,0-3.77,1.34A17.1,17.1,0,0,0,8.9,18.75L3.84,22.37a2,2,0,0,0,2.33,3.25l5.93-4.24,4.08,2.79-2,3.93a2,2,0,0,0,3.58,1.79l.45-.89H23a2,2,0,0,0,0-4H20.24L23,19.47l5.21,10.42a2,2,0,0,0,3.58-1.79Z"/></svg>`
const imgElement =  document.createElement('img');

class DraggableImage {
    constructor(imageSrc, parentElement) {
        this. imageSrc = imageSrc;
        this.parentElement = parentElement;

        imgElement.src = this.imageSrc;
        
        
        imgElement.style.position = 'absolute';
        imgElement.style.cursor = 'move';
        imgElement.style.zIndex = "1000"
        imgElement.style.top = '0px'; // 设置图片位于顶部
        imgElement.style.left = '0px'; // 设置图片位于左边

        this.parentElement.appendChild(imgElement);

        imgElement.onmousedown = function(event) {
            event.preventDefault();

            let shiftX = event.clientX - imgElement.getBoundingClientRect().left;
            let shiftY = event.clientY - imgElement.getBoundingClientRect().top;

            moveAt(event.pageX, event.pageY);

            function moveAt(pageX, pageY) {
                let left = pageX - shiftX;
                let top = pageY - shiftY;

                // 边界检查
                if (left < 0) left = 0;
                if (top < 0) top = 0;
                if (left > document.documentElement.clientWidth - imgElement.offsetWidth) {
                    left = document.documentElement.clientWidth - imgElement.offsetWidth;
                }
                if (top > document.documentElement.clientHeight - imgElement.offsetHeight) {
                    top = document.documentElement.clientHeight - imgElement.offsetHeight;
                }

                imgElement.style.left = left + 'px';
                imgElement.style.top = top + 'px';
            }

            function onMouseMove(event) {
                moveAt(event.pageX, event.pageY);
            }

            document.addEventListener('mousemove', onMouseMove);

            imgElement.onmouseup = function() {
                document.removeEventListener('mousemove', onMouseMove);
                imgElement.onmouseup = null;
            };

        };

        imgElement.ondragstart = function() {
            return false;
        };
    }
}

/*
这个createCustomContextMenu函数接受一个menuItems数组作为参数，
这个数组包含了你想要在菜单中显示的所有项。
每个项都是一个对象，包含text和action两个属性，分别表示菜单项的文本和点击时的动作。
*/

function createCustomContextMenu() {
    

    // 监听右键点击事件
    imgElement.addEventListener('contextmenu', function(e) {
        e.preventDefault();

        // 移除已存在的自定义菜单
        let existingMenu = document.querySelector('.custom-context-menu');
        if (existingMenu) {
            document.body.removeChild(existingMenu);
        }

        // 创建自定义菜单
        let contextMenu = document.createElement('div');
        contextMenu.classList.add('custom-context-menu');
        contextMenu.style.position = 'absolute';
        contextMenu.style.top = `${e.pageY}px`;
        contextMenu.style.left = `${e.pageX}px`;
        contextMenu.style.zIndex = "10000"

        // 添加菜单项
        let menuItems = FindCustomContextMenu();
        menuItems.forEach(item => {
            let menuItem = document.createElement('div');
            menuItem.textContent = item.text;
            menuItem.addEventListener('click', item.action);
            contextMenu.appendChild(menuItem);
        });

        // 将自定义菜单添加到页面
        document.body.appendChild(contextMenu);

        // 点击其他地方移除自定义菜单
        document.addEventListener('click', function() {
            document.body.removeChild(contextMenu);
        }, { once: true });
    });
}

function FindCustomContextMenu() {
    // 查询状态
    let translation_status;
    // chrome.runtime.sendMessage({ action: "translation_status" }, (response) => {
    //     console.log(response);
    //     if (response.result.message === "on") {
    //         // 翻译状态为开启，显示翻译图标
    //         translation_status = "取消翻译";
    //     } else {
    //         // 翻译状态为关闭，不显示翻译图标
    //         translation_status = "开启翻译";
    //     }
    // });

    new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
            { action: "translation_status" },
            (response) => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve(response);
                }
            }
        );
    })
        .then((response) => {
            console.log(response);
            if (response.result.message === "on") {
                // 翻译状态为开启，显示翻译图标
                translation_status = "取消翻译";
            } else {
                // 翻译状态为关闭，不显示翻译图标
                translation_status = "开启翻译";
            }
        })
        .catch((error) => {
            console.error(error);
        });

    let res = [];
    res = [
        {
            text: translation_status,
            action: function () {
                // 进行判断
                if (translation_status === "开启翻译") {
                    // 发送消息给后台，开启翻译
                    chrome.runtime.sendMessage({ action: "translation_on" });
                }else{
                    // 发送消息给后台，关闭翻译
                    chrome.runtime.sendMessage({ action: "translation_off" });
                }
            },
        },
        {
            text: "设置",
            action: function () {
                // 打开设置页面
            },
        },
    ];
    return res;
}

// 初始化翻译图标
function initTranslationIcon() {
    // 使用类创建一个新的可拖动的按钮，图标为 Font Awesome 的心形图标
    let myButton = new DraggableImage('data:image/svg+xml,' + encodeURIComponent(icon), document.body);

    // 创建一个自定义菜单，包含两个菜单项
    createCustomContextMenu([
        { text: '翻译', action: function () {
            // 存储数据到 local 存储区域
            chrome.storage.local.set({ 'setting': '测试' }, function() {
                console.log('Data has been set.');
            });
        } },
        { text: '设置', action: () => console.log('Second item clicked') }
    ]);
}




function test() {
    alert("测试")
}

function main() {
    // test();


    initTranslationIcon()
    // chrome.runtime.sendMessage({ action: "doSomething" }, (response) => {
    //     console.log(response.result); // 打印收到的响应
    // });
}
main()